package com.java.mywxmp.handler;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.java.mywxmp.builder.TextBuilder;
import com.java.mywxmp.entity.Message;
import com.java.mywxmp.entity.Reply;
import com.java.mywxmp.service.MessageService;
import com.java.mywxmp.service.ReplyService;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

import static me.chanjar.weixin.common.api.WxConsts.XmlMsgType;

@Component
@AllArgsConstructor
public class MsgHandler extends AbstractHandler {
    private final MessageService messageService;
    private final ReplyService replyService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) {

        if (!wxMessage.getMsgType().equals(XmlMsgType.EVENT)) {
            // 保存消息
            Message message = new Message();
            message.setToUser(wxMessage.getToUser());
            message.setFromUser(wxMessage.getFromUser());
            message.setCreateTime(new Date());
            message.setContent(wxMessage.getContent());
            message.setMsgType(wxMessage.getMsgType());
            message.setMenuId(wxMessage.getMenuId());
            message.setMsgId(wxMessage.getMsgId());
            messageService.save(message);
        }

        //当用户输入关键词如“你好”，“客服”等，并且有客服在线时，把消息转发给在线客服
        try {
            if (StringUtils.startsWithAny(wxMessage.getContent(), "你好", "客服")
                    && weixinService.getKefuService().kfOnlineList()
                    .getKfOnlineList().size() > 0) {
                return WxMpXmlOutMessage.TRANSFER_CUSTOMER_SERVICE()
                        .fromUser(wxMessage.getToUser())
                        .toUser(wxMessage.getFromUser()).build();
            }
        } catch (WxErrorException e) {
            e.printStackTrace();
        }

        // 根据用户输入关键词去数据库查询
        String content = wxMessage.getContent();
        Reply reply = replyService.getOne(new LambdaQueryWrapper<Reply>().eq(Reply::getKey, content));
        if (reply == null) {
            return new TextBuilder().build("未查询到有效信息,注意区分大小写!", wxMessage, weixinService);
        }
        return new TextBuilder().build(reply.getValue(), wxMessage, weixinService);

    }

}
